package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.CollectTemplate;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.TemplateMarketBo;
import org.dromara.admin.domain.vo.TemplateMarketVo;
import org.dromara.admin.domain.TemplateMarket;
import org.dromara.admin.mapper.TemplateMarketMapper;
import org.dromara.admin.service.ITemplateMarketService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 模板市场Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-09
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TemplateMarketServiceImpl implements ITemplateMarketService {

    private final TemplateMarketMapper baseMapper;
    private final IEmployeeService employeeService;

    /**
     * 查询模板市场
     *
     * @param id 主键
     * @return 模板市场
     */
    @Override
    public TemplateMarketVo queryById(Long id) {
        TemplateMarketVo templateMarketVo = baseMapper.selectVoById(id);
        if (BeanUtil.isEmpty(templateMarketVo)) {
            throw new ServiceException("模板信息不存在！");
        }
        return templateMarketVo;
    }

    /**
     * 分页查询模板市场列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 模板市场分页列表
     */
    @Override
    public TableDataInfo<TemplateMarketVo> queryPageList(TemplateMarketBo bo, PageQuery pageQuery) {
        // 查询用户信息
        EmployeeVo employeeVo = employeeService.queryById(bo.getLoginUserId());
        Long companyId = employeeVo.getCompanyId(); // 登录用户主体公司ID

        MPJLambdaWrapper<TemplateMarket> wrapper = new MPJLambdaWrapper<TemplateMarket>()
            .selectAll(TemplateMarket.class)
            // CASE WHEN 判断收藏状态
            .selectAs("CASE WHEN c.id IS NOT NULL THEN TRUE ELSE FALSE END", TemplateMarketVo::getIsCompanyCollected)
            .leftJoin(CollectTemplate.class, "c", w -> w.eq(CollectTemplate::getTemplateId, TemplateMarket::getId).eq(CollectTemplate::getCompanyId, companyId))
            .like(StrUtil.isNotBlank(bo.getTemplateName()), TemplateMarket::getTemplateName, bo.getTemplateName())
            .eq(bo.getPrintType() != null, TemplateMarket::getPrintType, bo.getPrintType())
            .eq(bo.getCategory() != null, TemplateMarket::getCategory, bo.getCategory())
            .orderByDesc(TemplateMarket::getCollectCount).orderByDesc(TemplateMarket::getUsedCount);
        Page<TemplateMarketVo> result = baseMapper.selectJoinPage(pageQuery.build(), TemplateMarketVo.class, wrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的模板市场列表
     *
     * @param bo 查询条件
     * @return 模板市场列表
     */
    @Override
    public List<TemplateMarketVo> queryList(TemplateMarketBo bo) {
        LambdaQueryWrapper<TemplateMarket> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TemplateMarket> buildQueryWrapper(TemplateMarketBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TemplateMarket> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TemplateMarket::getId);
        lqw.like(StringUtils.isNotBlank(bo.getTemplateCode()), TemplateMarket::getTemplateCode, bo.getTemplateCode());
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), TemplateMarket::getTemplateName, bo.getTemplateName());
        lqw.eq(bo.getPrintType() != null, TemplateMarket::getPrintType, bo.getPrintType());
        lqw.eq(bo.getCategory() != null, TemplateMarket::getCategory, bo.getCategory());
        return lqw;
    }

    /**
     * 新增模板市场
     *
     * @param bo 模板市场
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TemplateMarketBo bo) {
        TemplateMarket add = MapstructUtils.convert(bo, TemplateMarket.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模板市场
     *
     * @param bo 模板市场
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TemplateMarketBo bo) {
        TemplateMarket update = MapstructUtils.convert(bo, TemplateMarket.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TemplateMarket entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除模板市场信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 添加模板使用次数
     *
     * @param templateId 模板ID
     */
    @Override
    public void addTemplateUsedCount(Long templateId) {
        TemplateMarketVo templateMarketVo = this.queryById(templateId);
        templateMarketVo.setUsedCount(templateMarketVo.getUsedCount() + 1);
        Boolean b = this.updateByBo(BeanUtil.copyProperties(templateMarketVo, TemplateMarketBo.class));
        if (!b) {
            throw new ServiceException("添加模板使用次数失败！");
        }
    }

    /**
     * 添加模板收藏次数
     *
     * @param templateId 模板ID
     */
    @Override
    public void addTemplateCollectCount(Long templateId) {
        TemplateMarketVo templateMarketVo = this.queryById(templateId);
        templateMarketVo.setCollectCount(templateMarketVo.getCollectCount() + 1);
        Boolean b = this.updateByBo(BeanUtil.copyProperties(templateMarketVo, TemplateMarketBo.class));
        if (!b) {
            throw new ServiceException("添加模板收藏次数失败！");
        }
    }

    /**
     * 减少模板收藏次数
     *
     * @param templateId 模板ID
     */
    @Override
    public void reduceTemplateCollectCount(Long templateId) {
        TemplateMarketVo templateMarketVo = this.queryById(templateId);
        templateMarketVo.setCollectCount(templateMarketVo.getCollectCount() - 1);
        Boolean b = this.updateByBo(BeanUtil.copyProperties(templateMarketVo, TemplateMarketBo.class));
        if (!b) {
            throw new ServiceException("减少模板收藏次数失败！");
        }
    }
}
